<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="null">
    <meta name="keyword" content="null">
    <meta name="theme-color" content="#600090">
    <meta name="msapplication-navbutton-color" content="#600090">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#600090">
    <link rel="shortcut icon" href="/assets/favicon.ico">
    <link rel="alternate" type="application/atom+xml" title="张小阳" href="/atom.xml">
    <link rel="stylesheet" href="https://cdn.bootcss.com/animate.css/3.5.2/animate.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css">
    <title>
        
        正则表达式｜MillZhang&#39;s blog
        
    </title>

    <link rel="canonical" href="http://millzhang.github.io/2017/05/27/2017-note/06.正则表达式/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/blog-style.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">
</head>

<!-- hack iOS CSS :active style -->
<body ontouchstart="" class="animated fadeIn">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "true" data-istags="false
" data-ishome = "false" >
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand animated pulse" href="/">
                <span class="brand-logo">
                    MillZhang
                </span>
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <!-- /.navbar-collapse -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/"><i class="fa fa-home"></i>主页</a>
                    </li>
                   <li>
                        <a href="/tags"><i class="fa fa-tags"></i>归档</a>
                    </li>
                    <li>
                        <a href="/about"><i class="fa fa-user"></i>关于</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
//    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>

<!-- Main Content -->

<!--only post-->

<header class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <div class="post-heading">
                    <h1>正则表达式</h1>
                    
                    <span class="meta">
                         作者 MillZhang
                        <span>
                          日期 2017-05-27
                         </span>
                    </span>
                    <div class="tags text-center">
                        
                        <a class="tag" href="/tags/#正则"
                           title="正则">正则</a>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="post-title-haojen">
        <span>
            正则表达式
        </span>
    </div>
    <div class="post-header-image">
        
            <img src="http://oritfw5nq.bkt.clouddn.com/wall-303.jpg?imageView2/0/format/jpg/interlace/1/q/85|watermark/2/text/QnkgTWlsbHpoYW5n/font/5b6u6L2v6ZuF6buR/fontsize/480/fill/I0ZERkRGRA==/dissolve/56/gravity/SouthEast/dx/10/dy/10|imageslim">
         
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
            <!-- Post Container -->
            <div class="col-lg-8 col-lg-offset-1 col-sm-9 post-container">
                <h3 id="元字符"><a href="#元字符" class="headerlink" title="元字符"></a>元字符</h3><table>
<thead>
<tr>
<th style="text-align:center">代码</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>*</code></td>
<td>匹配重复任意次(包括0次)</td>
</tr>
<tr>
<td style="text-align:center"><code>+</code></td>
<td>匹配一次或多次(至少一次)</td>
</tr>
<tr>
<td style="text-align:center"><code>.</code></td>
<td>匹配除换行符以外的任意字符</td>
</tr>
<tr>
<td style="text-align:center"><code>\w</code></td>
<td>匹配字母或数字或下划线或汉字</td>
</tr>
<tr>
<td style="text-align:center"><code>\s</code></td>
<td>匹配任意的空白符，包括空格，制表符(Tab)，换行符，中文全角空格</td>
</tr>
<tr>
<td style="text-align:center"><code>\d</code></td>
<td>匹配数字</td>
</tr>
<tr>
<td style="text-align:center"><code>\b</code></td>
<td>匹配单词开始或结束</td>
</tr>
<tr>
<td style="text-align:center"><code>^</code></td>
<td>匹配字符串开始</td>
</tr>
<tr>
<td style="text-align:center"><code>$</code></td>
<td>匹配字符串结尾</td>
</tr>
</tbody>
</table>
<a id="more"></a>
<h3 id="字符转义"><a href="#字符转义" class="headerlink" title="字符转义"></a>字符转义</h3><p>如果想要查找匹配字符本身,则需要进行字符转义,转义符<code>\</code>,例如:<code>\.</code>,<code>\*</code>,<code>\\</code></p>
<h3 id="重复"><a href="#重复" class="headerlink" title="重复"></a>重复</h3><table>
<thead>
<tr>
<th>代码</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>*</code></td>
<td>重复0次或更多次</td>
</tr>
<tr>
<td><code>+</code></td>
<td>重复1次或更多次</td>
</tr>
<tr>
<td><code>?</code></td>
<td>重复0次或1次</td>
</tr>
<tr>
<td><code>{n}</code></td>
<td>重复n次</td>
</tr>
<tr>
<td><code>{n,}</code></td>
<td>重复n次或更多次</td>
</tr>
<tr>
<td><code>{n,m}</code></td>
<td>重复n到m次</td>
</tr>
</tbody>
</table>
<h3 id="字符类"><a href="#字符类" class="headerlink" title="字符类"></a>字符类</h3><p>在方括号<code>[]</code>里列出即可,如:<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">[a-zA-z0<span class="number">-9</span>]</div><div class="line">[abedcdoi?!]</div></pre></td></tr></table></figure></p>
<h3 id="分支条件"><a href="#分支条件" class="headerlink" title="分支条件"></a>分支条件</h3><p>用<code>|</code>将几种规则分割开,满足其中任意一种即匹配成功,栗子:</p>
<p><code>0\d{2}-\d{8}|0\d{3}-\d{7}</code>:这个表示<code>0</code>开头,然后<code>2</code>位数字,加<code>-</code>,加<code>8</code>位数字,或者<code>0</code>开头,加<code>3</code>位数字,加<code>-</code>,加<code>7</code>位数字,比方:<br><code>012-12345678</code>或者<code>0123-1234567</code></p>
<p>注意:匹配分枝条件时，将会从左到右地测试每个条件，如果满足了某个分枝的话，就不会去再管其它的条件了。所以特别要注意顺序</p>
<h3 id="分组"><a href="#分组" class="headerlink" title="分组"></a>分组</h3><p>分组是通过标识符<code>()</code>来进行整体的分组匹配的,栗子:</p>
<p>一个简单的ip匹配:<code>(\d{1,3}\.){3}\d{1,3}</code></p>
<p><code>\d{1,3}</code>匹配1到3位的数字，<code>(\d{1,3}\.){3}</code>匹配三位数字加上一个英文句号(这个整体也就是这个分组)重复3次，最后再加上一个一到三位的数字<code>(\d{1,3})</code></p>
<p>正确的ip匹配<code>((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)</code></p>
<h3 id="反义符"><a href="#反义符" class="headerlink" title="反义符"></a>反义符</h3><table>
<thead>
<tr>
<th>代码</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>\W</code></td>
<td>匹配任意不是字母，数字，下划线，汉字的字符</td>
</tr>
<tr>
<td><code>\S</code></td>
<td>匹配任意不是空白符的字符</td>
</tr>
<tr>
<td><code>\D</code></td>
<td>匹配任意非数字的字符</td>
</tr>
<tr>
<td><code>\B</code></td>
<td>匹配不是单词开头或结束的位置</td>
</tr>
<tr>
<td><code>[^x]</code></td>
<td>匹配除了x以外的任意字符</td>
</tr>
<tr>
<td><code>[^aeiou]</code></td>
<td>匹配除了aeiou这几个字母以外的任意字符</td>
</tr>
</tbody>
</table>
<h4 id="更多高级功能"><a href="#更多高级功能" class="headerlink" title="更多高级功能"></a>更多高级功能</h4><h4 id="后项引用"><a href="#后项引用" class="headerlink" title="后项引用"></a>后项引用</h4><p>使用小括号指定一个子表达式后，匹配这个子表达式的文本(也就是此分组捕获的内容)可以在表达式或其它程序中作进一步的处理。默认情况下，每个分组会自动拥有一个组号，规则是：从左向右，以分组的左括号为标志，第一个出现的分组的组号为1，第二个为2，以此类推。</p>
<p>后项引用就是:重复搜索前面某个分组匹配到的文本.<br>例如:<br><code>\b(\w+)\b\s+\1\b</code>可以用来匹配重复的单词，像<code>go go</code>, 或者<code>kitty kitty</code>。这个表达式首先是一个单词，也就是单词开始处和结束处之间的多于一个的字母或数字<code>(\b(\w+)\b)</code>，这个单词会被捕获到编号为1的分组中，然后是1个或几个空白符<code>(\s+)</code>，最后是分组1中捕获的内容（也就是前面匹配的那个单词）<code>(\1)</code>。<br>你也可以自己指定子表达式的组名。要指定一个子表达式的组名，请使用这样的语法：<code>(?&lt;Word&gt;\w+)</code>(或者把尖括号换成<code>&#39;</code>也行：<code>(?&#39;Word&#39;\w+))</code>,这样就把<code>\w+</code>的组名指定为<code>Word</code>了。要反向引用这个分组捕获的内容，你可以使用<code>\k&lt;Word&gt;</code>,所以上一个例子也可以写成这样：<code>\b(?&lt;Word&gt;\w+)\b\s+\k&lt;Word&gt;\b</code>。</p>
<p>常用的分组:</p>
<table>
<thead>
<tr>
<th>分类</th>
<th>代码</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>捕获</td>
<td><code>(exp)</code></td>
<td>匹配exp,并捕获文本到自动命名的组里</td>
</tr>
<tr>
<td></td>
<td><code>(?&lt;name&gt;exp)</code></td>
<td>匹配exp,并捕获文本到名称为name的组里，也可以写成(?’name’exp)</td>
</tr>
<tr>
<td></td>
<td><code>(?:exp)</code></td>
<td>匹配exp,不捕获匹配的文本，也不给此分组分配组号</td>
</tr>
<tr>
<td>零宽断言</td>
<td><code>(?=exp)</code></td>
<td>匹配exp前面的位置</td>
</tr>
<tr>
<td></td>
<td><code>(?&lt;=exp)</code></td>
<td>匹配exp后面的位置</td>
</tr>
<tr>
<td></td>
<td><code>(?!exp)</code></td>
<td>匹配后面跟的不是exp的位置</td>
</tr>
<tr>
<td></td>
<td><code>(?&lt;!exp)</code></td>
<td>匹配前面不是exp的位置</td>
</tr>
<tr>
<td>注释</td>
<td><code>(?#comment)</code></td>
<td>这种类型的分组不对正则表达式的处理产生任何影响，用于提供注释让人阅读</td>
</tr>
</tbody>
</table>
<h4 id="零宽断言"><a href="#零宽断言" class="headerlink" title="零宽断言"></a>零宽断言</h4><blockquote>
<p>断言用来声明一个应该为真的事实。正则表达式中只有当断言为真时才会继续进行匹配。<br><code>(?=exp)</code>,零宽度正预测先行断言,断言自身出现的位置的后面能匹配表达式exp —-以xxx结尾<br><code>(?&lt;=exp)</code>,宽度正回顾后发断言,断言自身出现的位置的前面能匹配表达式exp —-以xxx开头    </p>
</blockquote>
<h4 id="负向零宽断言"><a href="#负向零宽断言" class="headerlink" title="负向零宽断言"></a>负向零宽断言</h4><blockquote>
<p><code>(?!exp)</code>,零宽度负预测先行断言,断言此位置的后面不能匹配表达式exp —不以xxx结尾<br><code>(?&lt;!exp)</code>,零宽度负回顾后发断言,断言此位置的前面不能匹配表达式exp    —不以xxx开头</p>
</blockquote>
<h4 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h4><p><code>(?#comment)</code></p>
<h4 id="贪婪与懒惰"><a href="#贪婪与懒惰" class="headerlink" title="贪婪与懒惰"></a>贪婪与懒惰</h4><h4 id="处理选项"><a href="#处理选项" class="headerlink" title="处理选项"></a>处理选项</h4><h4 id="平衡组-递归匹配"><a href="#平衡组-递归匹配" class="headerlink" title="平衡组/递归匹配"></a>平衡组/递归匹配</h4><h4 id="More…"><a href="#More…" class="headerlink" title="More…"></a>More…</h4><h3 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h3><ol>
<li><a href="https://deerchao.net/tutorials/regex/regex.htm" target="_blank" rel="external">正则表达式30分钟入门指南</a></li>
<li><a href="https://msdn.microsoft.com/zh-cn/library/hs600312.aspx" target="_blank" rel="external">.NET Framework 正则表达式</a></li>
</ol>

                <hr>
                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2017/06/01/carts/01.书籍/" data-toggle="tooltip" data-placement="top"
                           title="书籍列表">&larr; 上一页</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2017/05/12/2017-note/05.JS笔录/" data-toggle="tooltip" data-placement="top"
                           title="JS随笔">下一页 &rarr;</a>
                    </li>
                    
                </ul>
                <div class="comment">
                    <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
                </div>
            </div>
            <div class="hidden-xs col-sm-3 toc-col">
                <div class="toc-wrap">
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#元字符"><span class="toc-text">元字符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#字符转义"><span class="toc-text">字符转义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#重复"><span class="toc-text">重复</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#字符类"><span class="toc-text">字符类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#分支条件"><span class="toc-text">分支条件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#分组"><span class="toc-text">分组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#反义符"><span class="toc-text">反义符</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#更多高级功能"><span class="toc-text">更多高级功能</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#后项引用"><span class="toc-text">后项引用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#零宽断言"><span class="toc-text">零宽断言</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#负向零宽断言"><span class="toc-text">负向零宽断言</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#注释"><span class="toc-text">注释</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#贪婪与懒惰"><span class="toc-text">贪婪与懒惰</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#处理选项"><span class="toc-text">处理选项</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#平衡组-递归匹配"><span class="toc-text">平衡组/递归匹配</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#More…"><span class="toc-text">More…</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#参考文档"><span class="toc-text">参考文档</span></a></li></ol>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                

                <!-- Friends Blog -->
                
            </div>
        </div>

    </div>
</article>
<!-- 网易云音乐-->

<iframe class="cloud-music" frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 
    src="//music.163.com/outchain/player?type=2&amp;id=18803411&amp;auto=0&amp;height=66">
</iframe>
<!-- 网易云跟帖-->
<script src="https://img1.cache.netease.com/f2e/tie/yun/sdk/loader.js"></script>
<script>
var cloudTieConfig = {
  url: document.location.href, 
  sourceId: "",
  productKey: "40a8ee22b6084862a8907e6902e525fa",
  target: "cloud-tie-wrapper"
};
var yunManualLoad = true;
Tie.loader("aHR0cHM6Ly9hcGkuZ2VudGllLjE2My5jb20vcGMvbGl2ZXNjcmlwdC5odG1s", true);
</script>

<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <p class="copyright text-muted">
                    Copyright &copy; MillZhang 2017
                    <br>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/blog.js"></script>

<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://oritfw5nq.bkt.clouddn.com/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>



<!--wechat title img-->
<img class="wechat-title-img" src="http://oritfw5nq.bkt.clouddn.com/avatar.jpg?imageslim">
<a id="backtop" class="border-bottom" href="javascript:;">回顶部</a>
<script type="application/javascript">
var docOuter = document.body.scrollTop ? document.body : document.documentElement;
var backToTop = function(rate) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  var top = function() {
    scrollTop = scrollTop + (0 - scrollTop) / (rate || 2);
    if (scrollTop < 1) {
      doc.scrollTop = 0;
      return;
    }
    doc.scrollTop = scrollTop;
    // 动画gogogo!
    requestAnimationFrame(top);
  };
  top();
};
var topBtn = document.getElementById('backtop'),
    docTop = docOuter.scrollTop;
if(docTop>=300){
  topBtn.style.opacity = 1;
}

topBtn.onclick = function() {
  backToTop(12)
}
window.onscroll = function(e) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  if (scrollTop >= 300) {
    topBtn.style.opacity = 1;
  } else {
    topBtn.style.opacity = 0;
  }
}
</script>
</body>

</html>
